package com.boot.dao;

import com.boot.entity.GpsInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xudi on 2/9/16.
 */
@Service
public class JdbcTemplatePostgisImpl{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<GpsInfo> executeQuery(final String sql) {
        return (List<GpsInfo>)jdbcTemplate.execute(stmt -> {
            ResultSet rs = stmt.executeQuery(sql);
            List<GpsInfo> list = new ArrayList<>();
            GpsInfo obj = null;
            while (rs.next()) {
                obj = new GpsInfo();
                obj.setId(rs.getInt("id"));
                obj.setBuildingId(rs.getInt("building_id"));
                obj.setDistance(rs.getDouble("st_distance"));
                list.add(obj);
            }
            return list;
        });
    }

    public Integer executeUpdate(final String sql) {
        return (Integer) jdbcTemplate.execute(stmt -> stmt.executeUpdate(sql));
    }

    public Boolean isExist(final String sql) {
        return (Boolean)jdbcTemplate.execute(stmt -> {
            Integer count=0;
            ResultSet rs = stmt.executeQuery(sql);
            if(rs.next()){
                count=rs.getInt(1);
            }
            return count>0;
        });
    }
}
